// 引入路由信息
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

import Login from '../pages/Login.vue'
import Register from '../pages/Register.vue'
import User from '../pages/User.vue'
import Edit from '../pages/Edit.vue'
import MyFollow from '../pages/MyFollow.vue'
import MyComments from '../pages/MyComments.vue'
import MyStar from '../pages/MyStar.vue'

// 参加路由
const router = new VueRouter({
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/register',
      component: Register
    },
    {
      path: '/user',
      component: User
    },
    {
      path: '/edit',
      component: Edit
    },
    {
      path: '/myfollow',
      component: MyFollow
    },
    {
      path: '/mycomments',
      component: MyComments
    },
    {
      path: '/my-star',
      component: MyStar
    }
  ]
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 导航守卫
// 1. to : 要访问的  路由对象
// 2. form : 从哪里过来  路由哦对象
// 3. next 允许访问
//  next() 允许访问
//  next(false) 不允许访问
router.beforeEach((to, from, next) => {
  let token = localStorage.getItem('token')

  const authUrl = ['/user', '/edit']

  if (authUrl.includes(to.path)) {
    if (token) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})

export default router
